package com.zayats.controller;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

import org.apache.avalon.framework.logger.Loggable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zayats.dal.FamilyRepository;
import com.zayats.exceptions.DataAccessDbException;
import com.zayats.exceptions.FamilyNotExistsException;
import com.zayats.model.Family;
import com.zayats.model.User;

@Controller
@RequestMapping(value="home/families")
public class FamilliesController {

	String errors;
	
	@Autowired
	FamilyRepository familyRepository;
	
	@RequestMapping(value = "/{username}")
	public @ResponseBody List<Family> families(@PathVariable String username, Model model, Principal principal) {
		List<Family> list = familyRepository.getFamiliesForUser(username);
		return list;
	}
	
	@RequestMapping(value = "/{familyId}/{username}")
	public @ResponseBody List<User> familyManager(@PathVariable String familyId, @PathVariable String username, Model model,
			Principal principal) {
		List<User> list = null;
		try {
			list = familyRepository.getParticipans(Integer.parseInt(familyId));
		} catch (FamilyNotExistsException e) {
			return null;
		} catch (EmptyResultDataAccessException e) {
			return null;
		}

		if (list.size() == 0)
			list = null;
		return list;
	}
	
	@RequestMapping(value = "/add/{name}/{username}")
	public @ResponseBody List<Boolean> familyAdd(@PathVariable String username, @PathVariable String name, Model model,
			Principal principal) {
		List<Boolean> result = new ArrayList<Boolean>();
		try {
			result.add(familyRepository.createFamily(name, username));
		} catch (DataAccessDbException e) {
			return null;
		}

		return result;
	}
	
	@RequestMapping(value = "/delete/{familyId}")
	public @ResponseBody List<Boolean> familyDelete(@PathVariable String familyId, Model model,
			Principal principal) {
		List<Boolean> result = new ArrayList<Boolean>();
		try {
			result.add(familyRepository.deleteFamily(Integer.parseInt(familyId)));
		} catch (DataAccessDbException e) {
			return null;
		}

		return result;
	}
}
